import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:schoollifedemo/business/school/viewmodel/memorandum_edit_page_viewmodel.dart';
import 'package:schoollifedemo/commonwidget/circle_empty_widget.dart';
import 'package:schoollifedemo/commonwidget/common_base_page.dart';
import 'package:schoollifedemo/commonwidget/common_dialog.dart';
import 'package:schoollifedemo/commonwidget/error_widget.dart';
import 'package:schoollifedemo/commonwidget/loading_widget.dart';
import 'package:schoollifedemo/commonwidget/text_widget_with_overflow.dart';
import 'package:schoollifedemo/commonwidget/textfield_widget.dart';
import 'package:schoollifedemo/entity/Entity.dart';

class EditMemorandumPage extends BaseStatefulPage {
  // 如果传入了noteId，说明为编辑已有的备忘录，否则为创建新的备忘录
  final String? noteId;
  final bool isEditMode;

  const EditMemorandumPage({Key? key, this.noteId, this.isEditMode = false})
      : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return _EditMemorandumPageState();
  }
}

class _EditMemorandumPageState extends BasePageState<EditMemorandumPage> {
  final _viewModel = MemorandumEditPageViewModel();
  bool _isTitleSelect = false;
  bool _isBodySelect = false;
  bool _isEdit = false;
  bool _isEditMode = false;
  bool _isModify = false;
  String _title = '';
  String _msg = '';

  String _lastTitle = '';
  String _lastMsg = '';
  final DateTime _createTime = DateTime.now();

  @override
  void initState() {
    _viewModel.init();
    _isEditMode = widget.isEditMode;
    _viewModel.currentNoteId = widget.noteId;
    if (widget.noteId?.isNotEmpty == true) {
      _viewModel.pullCurrentNote(
        noteId: widget.noteId!,
        onFailure: (msg) {
          DialogUtils.showTitleAndMessageDialog(context, title: '错误', msg: msg);
        },
      );
    } else {
      _viewModel.commonState();
    }
    super.initState();
  }

  @override
  void dispose() {
    _viewModel.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
        FocusScope.of(context).requestFocus(FocusNode());
      },
      child: StreamBuilder(
        initialData: CommonLoadingState.loading,
        stream: _viewModel.loadingState,
        builder: (buildContext, snapshot) {
          final loadingState = snapshot.data as CommonLoadingState?;
          switch (loadingState) {
            case CommonLoadingState.loading:
              return _loadingWidget();
            case CommonLoadingState.successTypeOne:
            case CommonLoadingState.successTypeTwo:
              return _commonBody();
            default:
              return _errorWidget();
          }
        },
      ),
    );
  }

  Widget _errorWidget() {
    return Scaffold(
      body: Container(
        color: Colors.white,
        child: CommonErrorWidget(
          '错误重试',
          onButtonClick: () async {
            _viewModel.pullCurrentNote(
              noteId: widget.noteId!,
              onFailure: (msg) {
                DialogUtils.showTitleAndMessageDialog(
                  context,
                  title: '错误',
                  msg: msg,
                );
              },
            );
          },
        ),
      ),
    );
  }

  Widget _loadingWidget() {
    return Scaffold(
      body: Container(
        color: Colors.white,
        child: const LoadingWidget(),
      ),
    );
  }

  Widget _commonBody() {
    return Scaffold(
      body: Container(
        padding: const EdgeInsets.only(top: 5, bottom: 20),
        color: Colors.white,
        child: ListView(
          physics: const BouncingScrollPhysics(),
          children: [
            Row(
              children: [
                GestureDetector(
                  onTap: () async {
                    // 不保存该备忘录
                    if (_isEdit) {
                      bool? trueOrFalse =
                          await DialogUtils.showCancelAndConfirmDialog(
                        context,
                        title: '提示',
                        msg: '已编辑，是否取消修改?',
                      );
                      if (trueOrFalse == true) {
                        // 取消更改时直接回退
                        _viewModel.backPage(context);
                      }
                    } else {
                      _viewModel.backPage(context);
                    }
                  },
                  child: Container(
                    margin: const EdgeInsets.only(left: 20),
                    child: const Icon(Icons.arrow_back_ios_outlined),
                  ),
                ),
                Expanded(
                  child: TextWidgetWithOverflow(
                    widget.noteId == null ? '你的备忘录' : '编辑备忘录',
                    fontSize: 28,
                    insideColor: Colors.transparent,
                    textAlign: TextAlign.left,
                  ),
                ),
                Offstage(
                  offstage: _isEditMode,
                  child: GestureDetector(
                    onTap: () async {
                      // edit mode
                      _isEditMode = !_isEditMode;
                      _isModify = true;
                      setState(() {});
                    },
                    child: Container(
                      margin: const EdgeInsets.only(right: 20),
                      child: const Icon(Icons.edit),
                    ),
                  ),
                ),
                Offstage(
                  offstage: _isEditMode,
                  child: GestureDetector(
                    onTap: () async {
                      // 删除该内容
                      bool? trueOrFalse =
                          await DialogUtils.showCancelAndConfirmDialog(
                        context,
                        title: '提示',
                        msg: '是否删除该备忘录',
                      );
                      if (trueOrFalse == true) {
                        // 取消更改时直接回退
                        _viewModel.deleteMemorandum();
                        _viewModel.backPage(context);
                      }
                    },
                    child: Container(
                      margin: const EdgeInsets.only(right: 20),
                      child: const Icon(Icons.delete),
                    ),
                  ),
                ),
                Offstage(
                  offstage: !_isEditMode,
                  child: GestureDetector(
                    onTap: () async {
                      // 保存备忘录
                      if (_title.isEmpty && _msg.isEmpty) {
                        Fluttertoast.showToast(
                          msg: '请先添加点东西',
                          gravity: ToastGravity.CENTER,
                        );
                        _isEditMode = !_isEditMode;
                        setState(() {});
                        return;
                      }
                      bool isChange = false;
                      // 内容一致无需修改
                      if (_msg != _lastMsg) {
                        isChange = true;
                      }
                      if (_title == _lastTitle) {
                        isChange = true;
                      }
                      if(widget.noteId == null){
                        isChange = true;
                      }
                      if (isChange) {
                        if (_title.isEmpty) {
                          _title = _viewModel.memorandumResponse
                                  ?.memorandumEntity?.title ??
                              '';
                        }
                        if (_msg.isEmpty) {
                          _msg = _viewModel
                                  .memorandumResponse?.memorandumEntity?.msg ??
                              '';
                        }

                        if (_isModify) {
                          await _viewModel.modifyMemorandum(
                            title: _title,
                            msg: _msg,
                            onFailure: (msg) {
                              DialogUtils.showTitleAndMessageDialog(
                                context,
                                clickOutSideDismiss: true,
                                title: "错误",
                                msg: "$msg",
                              );
                            },
                          );
                        } else {
                          await _viewModel.saveNewMemorandum(
                            title: _title,
                            msg: _msg,
                            createTime: _createTime,
                            onFailure: (msg) {
                              DialogUtils.showTitleAndMessageDialog(
                                context,
                                clickOutSideDismiss: true,
                                title: "错误",
                                msg: "$msg",
                              );
                            },
                            onSuccess: () {
                              if (_isModify) {
                                Fluttertoast.showToast(
                                  msg: '修改成功',
                                  gravity: ToastGravity.CENTER,
                                );
                              } else {
                                Fluttertoast.showToast(
                                  msg: '添加备忘录成功',
                                  gravity: ToastGravity.CENTER,
                                );
                              }
                            },
                          );
                        }
                      }
                      _lastMsg = _msg;
                      _lastTitle = _title;
                      _isEdit = false;
                      _isEditMode = !_isEditMode;
                      setState(() {});
                    },
                    child: Container(
                      margin: const EdgeInsets.only(right: 15),
                      child: const Icon(Icons.save_alt),
                    ),
                  ),
                ),
              ],
            ),
            Container(
              margin: const EdgeInsets.only(left: 20, right: 20, top: 10),
              child: CircleEmptyWidget(
                Column(
                  children: [
                    Container(
                      margin:
                          const EdgeInsets.only(left: 10, right: 10, top: 10),
                      child: Row(
                        children: [
                          const TextWidgetWithOverflow(
                            '标题: ',
                            fontSize: 18,
                            insideColor: Colors.transparent,
                            width: 100,
                          ),
                          Expanded(
                            child: TextFieldWidget(
                              insideColor: Colors.white,
                              cursorColor: Colors.black,
                              textColor: Colors.black,
                              maxLine: 1,
                              maxLength: 50,
                              isEnable: _isEditMode,
                              initText: _viewModel
                                  .memorandumResponse?.memorandumEntity?.title,
                              enableCountText: _isTitleSelect,
                              onFocus: (isFocus) {
                                _isTitleSelect = isFocus;
                                setState(() {});
                              },
                              onTextChange: (text) {
                                _title = text;
                                _isEdit = true;
                              },
                            ),
                          ),
                        ],
                      ),
                    ),
                    Container(
                      margin:
                          const EdgeInsets.only(left: 20, right: 20, top: 5),
                      child: TextWidgetWithOverflow(
                        '创建时间:${_viewModel.getCreateTime(time: _createTime)}',
                        fontSize: 12,
                        insideColor: Colors.transparent,
                        textAlign: TextAlign.left,
                        width: double.infinity,
                      ),
                    ),
                    Container(
                      margin:
                          const EdgeInsets.only(left: 20, right: 20, top: 5),
                      child: TextWidgetWithOverflow(
                        '上次编辑时间:${_viewModel.getLastEditTime(time: _createTime)}',
                        fontSize: 12,
                        insideColor: Colors.transparent,
                        textAlign: TextAlign.left,
                        width: double.infinity,
                      ),
                    ),
                    Container(
                      margin: const EdgeInsets.only(
                          left: 10, right: 10, top: 10, bottom: 10),
                      child: TextFieldWidget(
                        initText: _viewModel
                            .memorandumResponse?.memorandumEntity?.msg,
                        onTextChange: (text) {
                          _msg = text;
                          _isEdit = true;
                        },
                        onFocus: (isFocus) {
                          _isBodySelect = isFocus;
                          setState(() {});
                        },
                        maxLine: 20,
                        isEnable: _isEditMode,
                        keyboardType: TextInputType.multiline,
                        textColor: Colors.black,
                        cursorColor: Colors.black,
                        insideColor: Colors.transparent,
                        enableCountText: _isBodySelect,
                        maxLength: 500,
                        width: double.infinity,
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
